import { message } from "@/utils/message";
import { ElMessageBox, Sort } from "element-plus";
import { reactive, ref, onMounted, toRaw, computed } from "vue";
import { CommonUtils } from "@/utils/common";
import { PaginationProps } from "@pureadmin/table";
import {
  removeMemoTemplateByIdApi,
  queryMemoTemplateByConditionApi,
  QueryMemoTemplate,
  RemoveMemoTemplateById
} from "@/api/biz/strategy/memo";

export function useMemoHook() {
  const defaultSort: Sort = {
    prop: "id",
    order: "ascending"
  };

  const pagination: PaginationProps = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  };
  const dataList = ref([]);
  const pageLoading = ref(true);
  const multipleSelection = ref([]);

  const searchFormParams = reactive<QueryMemoTemplate>({
    name: undefined,
    memoTypeEnum: undefined,
    suggestStrategy: undefined,
    status: undefined,
    userId: undefined
  });

  const removeParams = reactive<RemoveMemoTemplateById>({
    id: undefined
  });

  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "Id",
      prop: "id",
      minWidth: 100
    },
    {
      label: "名称",
      prop: "name",
      minWidth: 100
    },
    {
      label: "备忘录类型",
      prop: "memoTypeEnum",
      minWidth: 120
    },
    {
      label: "建议攻略类型",
      prop: "suggestStrategy",
      minWidth: 120
    },
    {
      label: "当前状态",
      prop: "status",
      minWidth: 120
    },
    {
      label: "贡献人Id",
      prop: "userId",
      minWidth: 120
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];

  function onSortChanged() {
    // 表格列的排序变化的时候，需要重置分页
    pagination.currentPage = 1;
    getMemoList();
  }

  async function onSearch(tableRef) {
    // 点击搜索的时候，需要重置排序，重新排序的时候会重置分页并发起查询请求
    tableRef.getTableRef().sort("id", "ascending");
  }

  function resetForm(formEl, tableRef) {
    if (!formEl) return;
    // 清空查询参数
    formEl.resetFields();
    onSearch(tableRef);
  }

  async function getMemoList() {
    pageLoading.value = true;
    CommonUtils.fillBizPaginationParams(searchFormParams, pagination);
    const { data } = await queryMemoTemplateByConditionApi(searchFormParams).finally(() => {
      pageLoading.value = false;
    });
    dataList.value = data.results;
    pagination.total = data.total;
  }

  async function handleDelete(row) {
    removeParams.id = row.postId;
    await removeMemoTemplateByIdApi(removeParams).then(() => {
      message(`您删除了编号为${row.postId}的这条备忘录数据`, {
        type: "success"
      });
      // 刷新列表
      getMemoList();
    });
  }

  async function handleBulkDelete(tableRef) {
    if (multipleSelection.value.length === 0) {
      message("请选择需要删除的数据", { type: "warning" });
      return;
    }

    ElMessageBox.confirm(
      `确认要<strong>删除</strong>编号为<strong style='color:var(--el-color-primary)'>[ ${multipleSelection.value} ]</strong>的备忘录数据吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        removeParams.id = multipleSelection.value;
        await removeMemoTemplateByIdApi(removeParams).then(() => {
          message(`您删除了编号为[ ${removeParams.id} ]的备忘录数据`, {
            type: "success"
          });
          // 刷新列表
          getMemoList();
        });
      })
      .catch(() => {
        message("取消删除", {
          type: "info"
        });
        // 清空checkbox选择的数据
        tableRef.getTableRef().clearSelection();
      });
  }

  onMounted(getMemoList);

  return {
    defaultSort,
    searchFormParams,
    pagination,
    dataList,
    columns,
    pageLoading,
    multipleSelection,
    onSortChanged,
    resetForm,
    onSearch,
    getMemoList,
    handleDelete,
    handleBulkDelete
  };
}
